from datetime import datetime
import logging

import pytz
from core.entities.account_role import AccountWrap
from extensions.ext_database import db

from models.robot.rob_version import RobHardwareVersion
from services.errors.account import NotLoginError
from services.errors.versiions import RobHardwareVersionNotExistError
from services.log_service import LogAction, LogService
class VersionService:
    @staticmethod
    def get_h_ver_list(account:AccountWrap,args:dict)->list[RobHardwareVersion]:
        try:
            if not account or not hasattr(account, "current_tenant_id"):
                raise NotLoginError()
            tenant_id = account.current_tenant_id
            query = db.session.query(RobHardwareVersion).filter(RobHardwareVersion.tenant_id == tenant_id)
            if args.get("hardware_version",None):
                query = query.filter(RobHardwareVersion.ver.like(f"{args["ver"]}%"))
            # if args.get("is_force",None):
            #     query = query.filter(RobHardwareVersion.is_force==args["is_force"])
            if args.get("start",None):
                # db_user = AccountService.load_user(account.id,account.current_tenant_id)
                timezone = pytz.timezone('Asia/Shanghai')
                if account.timezone:
                    timezone = pytz.timezone(account.timezone)
                utc_timezone = pytz.utc
                start_datetime = datetime.strptime(args["start"], "%Y-%m-%d %H:%M")
                start_datetime = start_datetime.replace(second=0)

                start_datetime_timezone = timezone.localize(start_datetime)
                start_datetime_utc = start_datetime_timezone.astimezone(utc_timezone)
                if args.get("end",None):
                    end_datetime = datetime.strptime(args["start"], "%Y-%m-%d %H:%M")
                    end_datetime = end_datetime.replace(second=0)

                    end_datetime_timezone = timezone.localize(end_datetime)
                    end_datetime_utc = end_datetime_timezone.astimezone(utc_timezone)
                    query = query.filter(RobHardwareVersion.created_at <= end_datetime_utc,RobHardwareVersion.created_at >= start_datetime_utc)
                else:
                    query = query.filter(RobHardwareVersion.created_at >= start_datetime_timezone)
            versions = query.order_by(RobHardwareVersion.created_at.desc()).all()
            return versions
        except Exception as e:
            logging.error(e)
            raise e
        
    @staticmethod
    def create_h_ver(account:AccountWrap,ver:str,descrip:str,remote_ip:str)->RobHardwareVersion:
        try:
            if not account or not isinstance(account,AccountWrap):
                raise NotLoginError()
            tenant_id = account.current_tenant_id
            h_ver = RobHardwareVersion(
                tenant_id= tenant_id, # type: ignore
                ver = ver, # type: ignore
                descrip = descrip, # type: ignore
                created_at = datetime.now(), # type: ignore
                created_by = account.id # type: ignore
            )
            db.session.add(h_ver)
            LogService.log(
                tenant_id=tenant_id,
                account_id=account.id,
                action=LogAction.CREATE_HW_VER,
                content=f"{account.name} create hardware version {ver}",
                created_ip=remote_ip,
                submit=False
            )
            db.session.commit()
            return h_ver
        except Exception as e:
            db.session.rollback()
            raise e

    @staticmethod
    def del_h_ver(account:AccountWrap,ver_id:str,remote_ip:str):
        try:
            if not account or not isinstance(account,AccountWrap):
                raise NotLoginError()
            tenant_id = account.current_tenant_id
            h_ver = db.session.get(RobHardwareVersion,ver_id)
            if not h_ver:
                raise RobHardwareVersionNotExistError()
            ver = h_ver.ver
            db.session.delete(h_ver)
            LogService.log(
                tenant_id=tenant_id,
                account_id=account.id,
                action=LogAction.CREATE_HW_VER,
                content=f"{account.name} delete hardware version {ver}",
                created_ip=remote_ip,
                submit=False
            )
            db.session.commit()
            return h_ver
        except Exception as e:
            db.session.rollback()
            raise e
        
    @staticmethod
    def get_f_ver_list(account:AccountWrap,args:dict)->list[RobHardwareVersion]:
        try:
            if not account or not hasattr(account, "current_tenant_id"):
                raise NotLoginError()
            tenant_id = account.current_tenant_id
            query = db.session.query(RobHardwareVersion).filter(RobHardwareVersion.tenant_id == tenant_id)
            if args.get("hardware_version",None):
                query = query.filter(RobHardwareVersion.ver.like(f"{args["ver"]}%"))
            # if args.get("is_force",None):
            #     query = query.filter(RobHardwareVersion.is_force==args["is_force"])
            if args.get("start",None):
                timezone = pytz.timezone(account.timezone)
                utc_timezone = pytz.utc
                start_datetime = datetime.strptime(args["start"], "%Y-%m-%d %H:%M")
                start_datetime = start_datetime.replace(second=0)

                start_datetime_timezone = timezone.localize(start_datetime)
                start_datetime_utc = start_datetime_timezone.astimezone(utc_timezone)
                if args.get("end",None):
                    end_datetime = datetime.strptime(args["start"], "%Y-%m-%d %H:%M")
                    end_datetime = end_datetime.replace(second=0)

                    end_datetime_timezone = timezone.localize(end_datetime)
                    end_datetime_utc = end_datetime_timezone.astimezone(utc_timezone)
                    query = query.filter(RobHardwareVersion.created_at <= end_datetime_utc,RobHardwareVersion.created_at >= start_datetime_utc)
                else:
                    query = query.filter(RobHardwareVersion.created_at >= start_datetime_timezone)
            versions = query.order_by(RobHardwareVersion.created_at.desc()).all()
            return versions
        except Exception as e:
            logging.error(e)
            raise e